const util = require('../utils/util');
const wxApi = {
  __innerAudioContext: null,
  innerAudioContext() {
    if ( this.__innerAudioContext ) {
      return this.__innerAudioContext;
    }
    this.__innerAudioContext = wx.createInnerAudioContext();
    return this.__innerAudioContext;
  },
  /**
   * 开始下拉刷新
   *
   * @param {Function} callback
   */
  startRefresh( callback ) {
    wx.startPullDownRefresh({
      success() {
        callback( null );
      },
      fail() {
        callback( "refresh error!" );
      },
      complete() {

      }
    })
  },
  /**
   * 结束下拉刷新
   *
   */
  stopRefresh() {
    wx.stopPullDownRefresh();
  },
  /**
   * 路由跳转
   *
   * @param {String} path
   * @param {Object} params
   */
  navigateTo(path, params) {
    if ( params ) {
      path = path + "?" + util.querystring( params );
    }
    console.log(path);
    wx.navigateTo({
      url: path
    })
  },
  redirectTo(path, params) {
    if ( params ) {
      path = path + "?" + util.querystring( params );
    }
    console.log(path);
    wx.redirectTo({
      url: path
    })
  },
  /**
   * 设置导航栏标题
   *
   * @param {String} title
   */
  setNavTitle(title) {
    wx.setNavigationBarTitle({
      title: title || "朵威教育"
    });
  },
  toast(title, duration, icon) {
    wx.showToast({
      title: title,
      icon: 'none',
      duration: duration || 1500
    })
  },
  /**
   * 获取屏幕尺寸：width height
   *
   * @param {*} fn
   */
  getScreenSize(fn) {
    wx.getSystemInfo({
      success: function (res) {
        fn({
          width: res.windowWidth,
          height: res.windowHeight
        })
      }
    });
  },
  initAudioContext( params ) {
    console.log('create audio context');
    let innerAudioContext = wx.createInnerAudioContext();
    innerAudioContext.autoplay = params.autoplay === undefined ? false : params.autoplay;
    innerAudioContext.setSrc = ( val ) => {
      if ( innerAudioContext.src === val ) {
        innerAudioContext.seek(0);
        return;
      } 
      innerAudioContext.src = val;
    }
    innerAudioContext.src = params.src || '';
    innerAudioContext.onPlay(() => {
      params.onPlay && params.onPlay()
    })
    innerAudioContext.onEnded(() => {
      
    })
    innerAudioContext.onError((res) => {
      params.fail && params.fail()
    })
    return innerAudioContext;
  },
  playAudio( params ) {
    const innerAudioContext = wx.createInnerAudioContext();
    innerAudioContext.autoplay = params.autoplay === undefined ? true : params.autoplay;
    innerAudioContext.src = params.src;
    innerAudioContext.onPlay(() => {
      params.onPlay && params.onPlay()
    })
    innerAudioContext.onError((res) => {
      params.fail && params.fail()
    })
    return innerAudioContext;
  },
  /**
   * 本地数据缓存
   *
   * @param {String} key
   * @param {} data
   */
  setLocalAsync(key, data) {
    wx.setStorage({
      key: key, //
      data: data,
      success() {
        console.log('set ' + key + ' to local success...');
      }
    })
  },
  /**
   * 同步获取本地数据
   *
   * @param {String} key
   * @returns
   */
  getLocalSync( key ) {
    try {
      var data = wx.getStorageSync( key )
      if (data || data === false || data === 0) {
        console.log('get ' + key + ' success from local...')
        return data;
      }
      return null;
    } catch (e) {
      // Do something when catch error
    }
  },
  lastPage() {
    let pages = getCurrentPages();
    let lastPage = pages[pages.length - 2];
    return lastPage;
  },
  checkNetType() {
    let self = this;
    wx.getNetworkType( {
      success( network ) {
        let type = network.networkType;
        if ( type === '2g' ) {
          self.toast('当前网络不佳！');
        }
        if ( type === 'none' ) {
          self.toast('当前网络不可用!');
        }
      },
      fail( res ) {
        console.log( res );
        self.toast('请检查您的网络!');
      }
    } )
  },
  getLocation( fn) {
    wx.getLocation({
      success( obj ) {
        fn( obj );
      }
    })
  },
  /**
   * 序列化对象
   *
   * @param {Object} obj
   * @returns String
   */
  encodeURI( obj ) {
    obj = JSON.stringify( obj );
    obj = encodeURIComponent( obj );
    return obj;
  },
  /**
   * 反序列化
   *
   * @param {String} str
   * @returns Object
   */
  decodeURI( str ) {
    str = decodeURIComponent( str );
    str = JSON.parse( str );
    return str;
  },
}
module.exports = wxApi;